package com.onlinesys.protocol.dataprocessor.pool;

import java.util.Vector;

import org.apache.log4j.Logger;

import com.onlinesys.protocol.ConfigManager;
import com.onlinesys.protocol.ProtocolConstant;
import com.onlinesys.protocol.dataprocessor.processor.WriteDataProcessor;
import com.onlinesys.protocol.utils.ProtocolUtils;

public class DataWriteManager {
    public static Vector<WriteDataProcessor> vector;
    private static Logger logger = Logger.getLogger(DataWriteManager.class);

    public static void init() {
        String maxThreadStr = ConfigManager.getInstance().getConfig(ProtocolConstant.PARAMS_MAX_DATA_SEND_PROCESSOR, ProtocolConstant.PARAMS_MAX_DATA_SEND_PROCESSOR_DEFAULT_VALUE);
        int maxThread = Integer.parseInt(maxThreadStr);
        logger.info("Starting data write thread pool...");
        vector = new Vector<WriteDataProcessor>();
        for (int i = 1; i <= maxThread; i++) {
            WriteDataProcessor wdp = new WriteDataProcessor();
            vector.addElement(wdp);
            wdp.start();
        }
    }

    public static void process(byte[] argument) {
        int i;
        for (i = 0; i < vector.size(); i++) {
            WriteDataProcessor currentThread = (WriteDataProcessor) vector.elementAt(i);
            if (!currentThread.isRunning()) {
                logger.debug("Write Data Thread " + (i + 1) + " is processing:" + argument);
                //ProtocolUtils.printData(argument);
                currentThread.setArgument(argument);
                currentThread.setRunning(true);
                return;
            }
        }
        if (i == vector.size()) {
            logger.error("pool is full, data sent is failed. \n data:[");
            for (byte b : argument) {
                logger.error(b + " ");
            }
            logger.error("] \n No DataWriteProcess!");
        }
    }
}
